package cn.pugle.base.thread;

/**
 * @author tzp
 * @date 2017/11/17
 */
public class ThreadKillTest {

    public static void main(String[] args) {
        Runnable runnable = new MyRunnable2();

        //创建3个线程
        Thread thread1 = new Thread(runnable, "1");
        Thread thread2 = new Thread(runnable, "2");
        Thread thread3 = new Thread(runnable, "3");
        thread1.start();
        thread2.start();
        thread3.start();


        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                thread1.interrupt();
                System.out.println("Shutdown hook ran!");
            }
        });

        //线程休眠
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //修改退出标志，使线程终止
        thread1.interrupt();
        System.out.println("t1 isInter: " + thread1.isInterrupted());//todo 有时候true有时候false??
        thread2.interrupt();
        thread3.interrupt();
    }

    static class MyRunnable2 implements Runnable {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 线程创建");
            try {
                Thread.sleep(10000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
                //抛出这个异常的地方, 会clear调interrupt的标志, 所以下面使用false
            }
            //运行时的线程被中断后，只会修改中断标记，不会抛出异常. 抛出这个异常是sleep这个方法决定这样处理interrupt
            System.out.println(Thread.currentThread().isInterrupted());//始终false
            System.out.println(Thread.currentThread().getName() + " 线程到这了");
        }

    }
}
